<template>
  <el-container direction="vertical" id="user">
    <el-header>
      <h3>员工管理</h3>
    </el-header>
    
    <el-main>
      <div class="block-wrap" v-loading="loading">
          <el-button icon="el-icon-plus" class="margin-b-15" type="primary" size="small" @click="showDialog('new')">添加员工</el-button>
            <el-form :model="searchForm" ref="searchForm" :inline="true">
              <el-form-item>
                 <el-select v-model="searchForm.department_id" placeholder="请选择部门" clearable
                 @change="handleSelectStatus" size="small">
                  <el-option
                    v-for="item in department"
                  :key="item.department_id"
                  :label="item.name"
                  :value="item.department_id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="padding-t-4">
                <el-input v-model="searchForm.keyword" placeholder="请输入姓名或工号搜索" clearable size="small">
                  <el-button slot="append" @click="searchList" size="small"><i class="el-icon-search"></i>&nbsp;搜索</el-button>
                </el-input>
              </el-form-item>
            </el-form>
          <el-table :data="tableData" stripe center border>
            <el-table-column prop="name" label="姓名">
            </el-table-column>
            <el-table-column prop="sex" label="性别" width="80px">
              <template slot-scope="scope">{{scope.row.sex == 1 ? "男" : "女" }}
              </template>
            </el-table-column>
            <el-table-column prop="admin_tel" label="手机号">
            </el-table-column>
            <el-table-column prop="department_name" label="部门">
            </el-table-column>
            <el-table-column prop="job_number" label="工号">
            </el-table-column>
            <el-table-column label="操作" width="160px" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="disableUser(scope.row.user_id,scope.row.admin_status)">
                  {{scope.row.admin_status == 1?'禁用':'启用'}}
                </el-button>
                <el-button type="text" size="small" @click="edit(scope.row.user_id)">编辑</el-button>
                <el-button type="text" size="small" @click="resetPass(scope.row)">重设密码</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="margin-t-15"
            :current-page="$store.state.pagination.pageNum"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="20"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total" background>
          </el-pagination>
        </div>
        <!-- 弹框-员工 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="435px"
    :close-on-click-modal="false">
      <el-form :model="staffForm" label-position="right" :rules="rules" ref="staffForm">
        <el-form-item label="姓名:" :label-width="formLabelWidth" prop="name" >
          <el-input v-model.trim="staffForm.name" autocomplete="off" size="small" class="input250"  placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="工号:" :label-width="formLabelWidth" prop="job_number" >
          <el-input v-model.trim="staffForm.job_number" autocomplete="off" size="small" class="input250"placeholder="请输入员工工号"></el-input>
        </el-form-item>
        <el-form-item label="性别:" :label-width="formLabelWidth" size="small"  class="input250" prop="sex">
          <el-radio v-model="staffForm.sex" :label="1">男</el-radio>
          <el-radio v-model="staffForm.sex" :label="2">女</el-radio>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth" size="small">
          <el-upload
            :class="{'hide-last': staffForm.icon.length == 1}"
            :action="`${$common.basePath}/meeting/meeting/appImg`"
            list-type="picture-card"
            :on-success="(response, file) => {avatarSuccess('staffForm', response, file)}"
            :on-preview="avatarPreview"
            :on-remove="(file, fileList) => {avatarRemove('staffForm', file, fileList)}"
            :before-remove="beforeRemove"
            :file-list="staffForm.icon"
            :before-upload="beforeAvatarUpload"
            name="img">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog class="transparent-dialog" :visible.sync="avatarVisible" :append-to-body=true>
            <img width="100%" :src="imageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="手机号:" :label-width="formLabelWidth"
        prop="admin_tel">
          <el-input v-model.trim="staffForm.admin_tel" autocomplete="off" size="small"  
          class="input250" placeholder="请输入员工手机号"></el-input>
        </el-form-item>
        <el-form-item label="部门:" :label-width="formLabelWidth" prop="department_id">
          <el-select v-model="staffForm.department_id" placeholder="请选择部门" size="small" class="input250">
            <el-option
            v-for="item in department"
            :key="item.department_id"
            :label="item.name"
            :value="item.department_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色:" :label-width="formLabelWidth" prop="role_id">
          <el-select v-model="staffForm.role_id" placeholder="请选择角色" size="small" class="input250">
            <el-option
            v-for="obj in roles"
            :key="obj.role_id"
            :label="obj.name"
            :value="obj.role_id">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="tempOperateType == 'new'">
          <el-form-item label="密码:" :label-width="formLabelWidth" prop="admin_pwd">
            <el-input v-model.trim="staffForm.admin_pwd" type="password" autocomplete="off" class="input250" size="small" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" :label-width="formLabelWidth" prop="repeatPass">
            <el-input v-model.trim="staffForm.repeatPass" type="password" autocomplete="off" class="input250" size="small" placeholder="请再次输入密码"></el-input>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer align-center">
        <el-button @click="resetForm('staffForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('staffForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码弹框 -->
    <el-dialog title="重置密码" :visible.sync="dialogPwdVisible" width="440px"
    :close-on-click-modal="false"> 
      <el-form :model="pwdform" ref="pwdform" :rules="pwdRule" label-suffix="：">
        <p class="inline margin-l-45">姓名：{{username}}</p>
        <p class="inline margin-l-120">工号：{{userNum}}</p>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="admin_pwd">
          <el-input v-model.trim="pwdform.admin_pwd" type="password" autocomplete="off" size="small" placeholder="请输入新密码" class="input250"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="repeatPassword">
          <el-input v-model.trim="pwdform.repeatPassword" type="password" autocomplete="off" size="small" placeholder="请再次输入密码" class="input250"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer align-center">
        <el-button @click="resetPwd('pwdform')">取 消</el-button>
        <el-button type="primary" @click="submitPwd('pwdform')">确 定</el-button>
      </div>
    </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
  export default {
    data () {
      var validateTel = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入手机号'))
        } else if (!(/^1[3456789]\d{9}$/.test(value))) {
          callback(new Error('手机号不正确'))
        } else {
          if (!this.staffForm.admin_tel) {
            this.$refs.staffForm.validateField('admin_tel')
          }
          callback()
        }
      }
      var passwordValidate = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.staffForm.admin_pwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      var validatejob = (rule, value, callback) => {
        var reg = /[^\d.]/g
        if (!value) {
          callback(new Error('请输入员工工号'))
        } else if (reg.test(value)) {
          callback(new Error('请输入数字'))
        } else {
          if (!this.staffForm.job_number) {
            this.$refs.staffForm.validateField('job_number')
          }
          callback()
        }
      }
      var validatePwd = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.pwdform.admin_pwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
      var uploadValid = (rule, value, callback) => {
          if (!!value && value.length > 0) {
            callback();
          } else {
            callback(new Error('请上传图片'));
          }
        };
      return {
        dialogTitle: null,
        formLabelWidth: '100px',
        tempOperateType: 'new', // 操作类型 new新增 edit编辑
        department:[],
        roles:[],
        department: [],
        searchForm: {
          department_id: '',
          keyword: null
        },
        tableData: [],
        total: 0,
        dialogFormVisible: false,
        staffForm: {
          name: null,
          job_number: null,
          sex:        1,
          admin_tel:  null,
          department_id: null,
          role_id:    null,
          admin_pwd:  null,
          repeatPass: null,
          icon:        [],
        },
        rules: {
          name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
          job_number: [{ required: true, validator: validatejob, trigger: 'blur' }],
          sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
          admin_tel: [{ required: true, validator: validateTel, trigger: 'blur' }],
          department_id: [{ required: true, message: '请选择部门', trigger: 'change' }],
          role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
          admin_pwd: [{ required: true, min: 6, max: 12, message: '请输入密码, 密码长度为6-12',
                      trigger: 'blur'},
                      { pattern: this.$common.normalPassword, message: '密码必须是6到12位的数字或字母'}],
          repeatPass: [{ required: true,min: 6, max: 12, validator: passwordValidate,
                        trigger: 'blur' },
                      { pattern: this.$common.normalPassword, message: '密码必须是6到12位的数字或字母'}],
        },
        dialogPwdVisible: false,
        pwdform: {
          admin_pwd:      null,
          repeatPassword: null
        },
        username: null,//姓名
        userNum:  null,//工号
        pwdRule: {
          admin_pwd: [{ required: true, min: 6, max: 12, message: '请输入密码, 密码长度为6-12',
                      trigger: 'blur'},
                      { pattern: this.$common.normalPassword, message: '密码必须是6到12位的数字或字母'}],
          repeatPassword: [{ required: true,min: 6, max: 12, validator: validatePwd,
                        trigger: 'blur' },
                      { pattern: this.$common.normalPassword, message: '密码必须是6到12位的数字或字母'}]
        },
        resetId:'',
        loading:false,
        currentId:'',//列表一条数据ID
        avatarVisible:false,
        imageUrl: '',
        admin_status: 1,//1启用，2禁用
      }
    },
    mounted () {
      this.showList()
      this.getDepartment()
      this.getRoles()
    },
    methods: {
       // 户型图
      avatarRemove(formName, file, fileList) {
        this[formName].icon = fileList;
        // this.$refs[formName].validateField('img')
      },
      avatarPreview(file) {
        this.imageUrl = file.url;
        this.avatarVisible = true;
      },
      //户型图图片上传成功
      avatarSuccess(formName, response, file) {
        this[formName].icon.push(file);
        console.log(this[formName].icon);
        // this.$refs[formName].validateField('img')
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG= file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除？`);
      },
      /**
       * 部门下拉搜索
       */
      handleSelectStatus(){
        this.showList()
      },
      // 搜索
      searchList(){
        this.$store.commit('changePage', 1)
        this.showList()
      },
      /**
       * 部门数据
       * @return {[type]} [description]
       */
      getDepartment () {
        let config = {
          method: 'post',
          url: `meeting/staff/getDepartment`,
          data: {admin_id: sessionStorage.getItem('admin_id')}
        }
        this.$axios(config).then(response => {
          this.department = response.data
        }).catch(error => {
          this.$message.error(error.msg)
        })
      },
      /**
       * 角色数据
       * @return {[type]} [description]
       */
      getRoles () {
        let config = {
          method: 'post',
          url: `meeting/staff/getRole`,
          data: {admin_id: sessionStorage.getItem('admin_id')}
        }
        this.$axios(config).then(response => {
          this.roles = response.data
        }).catch(error => {
          this.$message.error(error.msg)
        })
      },
      /**
         * 显示新增/编辑 对话框
         * @param  {[type]} type 操作类型
         * @param  {[type]} obj 当前操作的数据
         * @return {[type]}      [description]
         */
      showDialog (type, obj) {
        this.tempOperateType = type
        this.dialogTitle = '添加员工'
        if (type == 'new') {
          this.staffForm = {
            name:          null,
            job_number:    null,
            sex:           1,
            admin_tel:     null,
            department_id: null,
            role_id:       null,
            admin_pwd:     null,
            repeatPass:    null,
            icon:           [],
          }
        }
        this.dialogFormVisible = true
        // 清除验证信息
        this.$nextTick(_ => {
          this.$refs.staffForm.clearValidate()
        })
      },

      handleCurrentChange (val) {
        this.$store.commit('changePage', val)
        this.showList()
      },
      // 列表
      showList () {
        let config = {
          method: "post",
          data: this.searchForm,
          url:  `meeting/staff/showStaff`
          }
          config.data.p = this.$store.state.pagination.pageNum
          config.data.admin_id = this.$store.state.userData.admin_id
          this.loading = true
          this.$axios(config).then(response => {
            this.loading = false
            this.tableData = response.data.data
            this.total = response.data.total
          }).catch(error => {
            this.loading = false
            this.$message.error(error.msg)
          })
        },
      // 编辑
      edit (userId) {
        this.getDepartment()
        this.getRoles()
        this.dialogTitle = '编辑员工'
        this.tempOperateType = 'edit'
        let config = {
          method: 'post',
          data: { user_id: userId },
          url: `meeting/staff/detailStaff`
        }
        this.$axios(config).then(response => {
          let obj = this.$common.deepCopy(response.data)
          if(obj.icon && obj.icon != null){
            obj.icon = obj.icon.map(item => {
              return {
                  url:`${this.$common.filePath}${item}`,
                  name: '',
                  response: {
                    code: 200,
                    data: item
                  }
              }
            })
          }else{
            obj.icon = []
          }
          this.staffForm = obj
          // console.log(this.staffForm)
          this.dialogFormVisible = true
          // 清除验证信息
          this.$nextTick(_ => {
            this.$refs.staffForm.clearValidate()
          })
        }).catch(error => {
          this.$message.error(error.msg)
        })
      },
      /**
       *
       * @param formName
       */
      // 提交
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let obj = this.$common.deepCopy(this.staffForm)
            obj.icon = obj.icon.map(item => {
              return item.response.data
            })

            if (obj.admin_pwd !== obj.repeatPass) {
              this.$message.error('密码不一致')
            } else {
              let config = {
                method: 'post',
                data: obj,
                url: ''
              }
              config.data.admin_id = sessionStorage.getItem('admin_id')
              if (this.tempOperateType == 'new') {
                config.url = `meeting/staff/createStaff`
              } else if (this.tempOperateType == 'edit') {
                config.url = `meeting/staff/editStaff`
              }
              this.$axios(config).then(response => {
                console.log(response)
                this.$message.success(response.msg)
                this.dialogFormVisible = false
                this.showList()
              }).catch(error => {
                console.log(error)
                this.$message.error(error.msg)
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 取消
      resetForm (formName) {
        this.dialogFormVisible = false
      },
      // 删除
      deletes (row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let config = {
            method: 'post',
            data: { admin_id: row.admin_id },
            url: `${this.$common.basePath}/manage/staff/deleteStaff`
          }
          this.$axios(config).then(response => {
            if (response.data == 200) {
              this.$message.success('删除成功')
            }
            this.showList()
          }).catch(error => {
            this.$message.error(error.msg)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 重置密码--弹框
      resetPass (obj) {
        this.resetId = obj.user_id
        this.username = obj.name
        this.userNum = obj.job_number
        this.dialogPwdVisible = true
        // 清除验证信息
        this.$nextTick(_ => {
          this.$refs.pwdform.clearValidate()
          this.pwdform.admin_pwd = ''
          this.pwdform.repeatPassword = ''
        })
      },
      // 重置密码--取消
      resetPwd (formName) {
        this.dialogPwdVisible = false
      },
      // 重置密码--确认
      submitPwd (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.pwdform.admin_pwd !== this.pwdform.repeatPassword) {
              this.$message.error('密码不一致')
            } else {
              let config = {
                method: 'post',
                data: { user_id: this.resetId, admin_pwd: this.pwdform.admin_pwd },
                url: `meeting/staff/updatePassword`
              }
              this.$axios(config).then(response => {
                this.$message.success('修改成功')
                this.dialogPwdVisible = false
                this.showList()
              }).catch(error => {
                this.$message.error(error.msg)
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 取消
      resetForm (formName) {
        this.dialogFormVisible = false
      },
      /**
       * 禁用或启用员工
       */
      disableUser(id,status){
        //当前状态是启用（1）就要传2.
        let type = status == 1?2:1
        let config = {
          method: "post",
          url:    "meeting/staff/setState",
          data:   { user_id: id, admin_status: type}
        }
        this.$axios(config).then(res => {
          this.$message.success(res.msg)
          this.showList()
        }).catch(err => {
          this.$message.error(err.msg)
        })
      }
    }
  }
</script>
<style type="text/css" lang="less" scoped>
  .header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  .input250{
    width: 250px;
  }
  .inline{
    display: inline-flex;
  }
  .margin-l-45{
    margin-left: 45px;
  }
  .margin-l-120{
    margin-left: 120px;
  }
  .padding-t-4{
    padding-top:4px;
  }
</style>
<style type="text/css" lang="less">
  #user{
    /**
     * 上传图片大小
     */
    .el-upload-list--picture-card .el-upload-list__item{
      width: 95px;
      height: 95px;
    }
    .el-upload--picture-card{
      width: 95px;
      height: 95px;
      line-height: 103px;
    }
  }
</style>